package com.my12306.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.my12306.models.TicketQuery;
import com.my12306.models.TrainEnquiries;
import com.my12306.service.impl.ServiceManager;
import com.my12306.util.StationAll;
@Controller
@RequestMapping
public class TicketController {
	@Autowired
	private ServiceManager sm;
	@RequestMapping(value = "/m")
	public String test(){
		return "index2";
	}
	@RequestMapping(value = "/ticket/query")
	public ModelAndView queryTicket(@RequestParam String from, @RequestParam String to, @RequestParam String date) throws Exception{
		ModelAndView mav = new ModelAndView();
		System.out.println(from + " " + to + " " + date);
		String from_station = StationAll.getStationCode(from);
		String to_station = StationAll.getStationCode(to);
		if(from_station != null && to_station != null){
			String result = sm.getTicKetService().httpQueryTicket(date, from_station, to_station);
			Gson gson = new Gson();
			TicketQuery tq = gson.fromJson(result, TicketQuery.class);
			tq.initIsGD();
			mav.setViewName("index");
			List<TrainEnquiries> trains = tq.getData().getDatas();
			//Model m = new 
			String test = "testtest";
			mav.addObject("test", test);
			mav.addObject("from", from);
			mav.addObject("to", to);
			mav.addObject("date", date);
			mav.addObject("trains", trains);
		}else{
			mav.setViewName("error");
		}
		return mav;
	}
	
	@RequestMapping(value = "/ticket/mquery")
	public ModelAndView mQueryTicket(@RequestParam String from, @RequestParam String to, @RequestParam String date) throws Exception{
		ModelAndView mav = new ModelAndView();
		System.out.println(from + " " + to + " " + date);
		String from_station = StationAll.getStationCode(from);
		String to_station = StationAll.getStationCode(to);
		if(from_station != null && to_station != null){
			String result = sm.getTicKetService().httpQueryTicket(date, from_station, to_station);
			Gson gson = new Gson();
			TicketQuery tq = gson.fromJson(result, TicketQuery.class);
			mav.setViewName("result");
			List<TrainEnquiries> trains = tq.getData().getDatas();
			//Model m = new 
			String test = "testtest";
			mav.addObject("test", test);
			mav.addObject("from", from);
			mav.addObject("to", to);
			mav.addObject("date", date);
			mav.addObject("trains", trains);
		}else{
			mav.setViewName("error");
		}
		return mav;
	}

	public ServiceManager getSm() {
		return sm;
	}

	public void setSm(ServiceManager sm) {
		this.sm = sm;
	}
	
}
